package me.nereo.multi_image_selector.adapter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.ali.music.multi_image_selector.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import me.nereo.multi_image_selector.bean.Image;

/**
 * 图片Adapter
 * Created by Nereo on 2015/4/7.
 */
public class ImageGridAdapter extends BaseAdapter {

    private static final int TYPE_CAMERA = 0;
    private static final int TYPE_NORMAL = 1;
    private int mCurMode = 0;

    private Context mContext;

    private LayoutInflater mInflater;
    private boolean mShowCamera = true;
    private boolean mShowSelectIndicator = true;

    private List<Image> mImages = new ArrayList<>();
    private List<Image> mSelectedImages = new ArrayList<>();

    private int mItemSize;
    private GridView.LayoutParams mItemLayoutParams;
    private OnPhotoItemCheckedListener mOnPhotoItemCheckedListener;

    /**
     * @param listener OnPhotoItemCheckedListener
     */
    public void setOnPhotoItemCheckedListener(OnPhotoItemCheckedListener listener) {

        mOnPhotoItemCheckedListener = listener;
    }

    /**
     *
     */
    public interface OnPhotoItemCheckedListener {
        /**
         * @param holde       BaseHolder
         * @param convertView view
         */
        public void onViewClick(BaseHolder holde, View convertView);
    }

    /**
     * @param context    Context
     * @param showCamera true
     * @param curMode    mode
     */
    public ImageGridAdapter(Context context, boolean showCamera, int curMode) {
        mContext = context;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.mShowCamera = showCamera;
        this.mCurMode = curMode;
        mItemLayoutParams = new GridView.LayoutParams(GridView.LayoutParams.MATCH_PARENT, GridView.LayoutParams.MATCH_PARENT);
    }

    /**
     * 显示选择指示器
     *
     * @param b true
     */
    public void showSelectIndicator(boolean b) {
        mShowSelectIndicator = b;
    }

    /**
     * @param b true
     */
    public void setShowCamera(boolean b) {
        if (mShowCamera == b) {
            return;
        }

        mShowCamera = b;
        notifyDataSetChanged();
    }

    /**
     * @return true showing
     */
    public boolean isShowCamera() {
        return mShowCamera;
    }

    /**
     * 选择某个图片，改变选择状态
     *
     * @param holder BaseHolder
     */
    public void select(BaseHolder holder) {
        if (holder instanceof ViewHolder) {
            Image image = holder.mData;
            if (mSelectedImages.contains(image)) {
                mSelectedImages.remove(image);
            } else {
                mSelectedImages.add(image);
            }
            ((ViewHolder) holder).bindData(holder.mPosition);
        }
    }

    /**
     * 通过图片路径设置默认选择
     *
     * @param resultList ArrayList
     */
    public void setDefaultSelected(ArrayList<String> resultList) {
        if (mSelectedImages != null) {
            mSelectedImages.clear();
        }
        for (String path : resultList) {
            Image image = getImageByPath(path);
            if (image != null) {
                mSelectedImages.add(image);
            }
        }
        notifyDataSetChanged();
    }

    private Image getImageByPath(String path) {
        if (mImages != null && mImages.size() > 0) {
            for (Image image : mImages) {
                if (image.mPath.equalsIgnoreCase(path)) {
                    return image;
                }
            }
        }
        return null;
    }

    /**
     *
     * @return list
     */
    public List<Image> getData() {
        return mImages;
    }

    /**
     * @param image    Image
     * @param index    in
     * @param selected boolean
     */
    public void setNewCamera(Image image, int index, boolean selected) {
        mImages.add(index, image);
        if (selected) {
            mSelectedImages.add(image);
        }
        notifyDataSetChanged();
    }

    /**
     * 设置数据集
     *
     * @param images List
     */
    public void setDatas(List<Image> images) {
        mSelectedImages.clear();

        if (images != null && images.size() > 0) {
            mImages = images;
        } else {
            mImages.clear();
        }
        notifyDataSetChanged();
    }

    /**
     * 重置每个Column的Size
     *
     * @param columnWidth int
     */
    public void setItemSize(int columnWidth) {

        if (mItemSize == columnWidth) {
            return;
        }

        mItemSize = columnWidth;

        mItemLayoutParams = new GridView.LayoutParams(mItemSize, mItemSize);

        notifyDataSetChanged();
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if (mShowCamera) {
            return position == 0 ? TYPE_CAMERA : TYPE_NORMAL;
        }
        return TYPE_NORMAL;
    }

    @Override
    public int getCount() {
        return mShowCamera ? mImages.size() + 1 : mImages.size();
    }

    @Override
    public Image getItem(int i) {
        if (mShowCamera) {
            if (i == 0) {
                return null;
            }
            return mImages.get(i - 1);
        } else {
            return mImages.get(i);
        }
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        int type = getItemViewType(i);
        if (type == TYPE_CAMERA) {
//            if(view == null){
            view = mInflater.inflate(R.layout.multi_list_item_camera, viewGroup, false);
            BaseHolder baseHolde = new BaseHolder(view);
            baseHolde.mPosition = i;
//            }
        } else if (type == TYPE_NORMAL) {
            ViewHolder holde;
//            if(view == null){
            view = mInflater.inflate(R.layout.multi_list_item_image, viewGroup, false);
            holde = new ViewHolder(view);
//            }else{
//                BaseHolder baseHolder = (BaseHolder) view.getTag();
//                if(baseHolder instanceof ViewHolder){
//                    holde = (ViewHolder) baseHolder;
//                }else{
//                    baseHolder.clear();
//                    view = mInflater.inflate(R.layout.multi_list_item_image, viewGroup, false);
//                    holde = new ViewHolder(view);
//                }
//            }
            if (holde != null) {
                holde.bindData(i);
            }
        }

        /** Fixed View Size */
        GridView.LayoutParams lp = (GridView.LayoutParams) view.getLayoutParams();
        if (lp.height != mItemSize) {
            view.setLayoutParams(mItemLayoutParams);
        }

        return view;
    }

    public class BaseHolder implements View.OnClickListener {
        /**
         *
         */
        public View mParent;
        /**
         *
         */
        public Image mData;
        /**
         *
         */
        public int mPosition;

        /**
         *
         * @param view View
         */
        public BaseHolder(View view) {
            mParent = view;
            mParent.setTag(this);
            mParent.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mOnPhotoItemCheckedListener != null) {
                mOnPhotoItemCheckedListener.onViewClick(this, view);
            }
        }

        /**
         * clear
         */
        public void clear() {
            mParent.setOnClickListener(null);
            mParent = null;
            mData = null;
        }
    }

    /**
     *
     */
    public class ViewHolder extends BaseHolder {
        private ImageView mImageView;
        private ImageView mIndicator;
        private View mMask;

        @Override
        public void clear() {
            super.clear();
            mImageView.setOnClickListener(null);
            mIndicator.setOnClickListener(null);
            mImageView = null;
            mIndicator = null;
            mMask = null;
        }

        /**
         *
         * @param view View
         */
        public ViewHolder(View view) {
            super(view);
            mImageView = (ImageView) view.findViewById(R.id.image);
            mIndicator = (ImageView) view.findViewById(R.id.cb_photo_lpsi);
            mMask = view.findViewById(R.id.mask);
            mIndicator.setOnClickListener(this); // CheckListener
        }

        /**
         *
         * @param position int
         */
        public void bindData(int position) {
            this.mPosition = position;
            this.mData = getItem(position);
            if (mData == null) {
                return;
            }

            // 处理单选和多选状态
            if (mShowSelectIndicator) {
                mIndicator.setVisibility(View.VISIBLE);
                int index = mSelectedImages.indexOf(mData);
                if (mSelectedImages.contains(mData)) {
                    //设置选中顺序
                    // 设置选中状态
                    mIndicator.setImageResource(R.drawable.multi_default_check_s);
                    mMask.setVisibility(View.VISIBLE);
                } else {
                    // 未选择
                    mIndicator.setImageBitmap(null);
                    mMask.setVisibility(View.GONE);
                }
            } else {
                mIndicator.setVisibility(View.GONE);
            }
            File imageFile = new File(mData.mPath);
            if (mItemSize > 0) {
                // 显示图片
//                Picasso.with(mContext)
//                        .load(imageFile)
//                        .placeholder(R.drawable.multi_default_error)
//                        .resize(mItemSize, mItemSize)
//                        .centerCrop()
//                        .into(mImageView);
                Glide.with(mContext)
                        .load(imageFile)
//                        .placeholder(R.drawable.multi_default_error)
                        .error(R.drawable.multi_default_error)
                        .override(mItemSize, mItemSize)
                        .centerCrop()
                    .listener(new RequestListener<File, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, File model, Target<GlideDrawable> target,
                                                   boolean isFirstResource) {
                            Log.e("致伟", this.getClass().getSimpleName() + " onResourceReady: model=" + model);
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, File model, Target<GlideDrawable> target,
                                                       boolean isFromMemoryCache, boolean isFirstResource) {
                            Log.e("致伟", this.getClass().getSimpleName() + " onResourceReady: model=" + model);
                            return false;
                        }
                    })
                        .into(mImageView);
            }
        }
    }

}
